package com.hethongviet.vending.pages;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hethongviet.vending.AppConfig;
import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Constant;
import com.google.android.DemoKit.R;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.helper.CodeResult;
import com.hethongviet.vending.helper.TimerOutUtils;
import com.hethongviet.vending.helper.db.MachineSQLite;
import com.hethongviet.vending.helper.dialog.DialogEditDomainName;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.helper.dialog.DialogMessageConfirm;
import com.hethongviet.vending.model.MachineInfo;
import com.hethongviet.vending.model.Transaction;
import com.hethongviet.vending.network.Network;

public class AdminActivity extends GeneralActivity
{
	public static final int REQUEST_EDIT_MAC_ADDRESS = 5;

	private LinearLayout _listViewMacAddress = null;

	private Button _buttonAddMacAddress = null;
	private Button _buttonModifyMachineCode = null;
	private Button _buttonModifyUsername = null;
	private Button _buttonModifyPassword = null;
	private Button _buttonModifyDatabase = null;

	private TextView _TextMachineCode = null;
	private TextView _TextUsername = null;
	private EditText _TextPassword = null;
	private TextView _TextDatabase = null;

	private TimerOutUtils _timerOutUtils = null;

	private static class ViewHolderMacAddress
	{
		TextView textMacAddress = null;
		Button buttonModify = null;
		Button buttonDelete = null;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.page_admin);

		findViewById(R.id.button_back).setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				finish();
			}
		});

		// ((TextView) findViewById(R.id.text_user_name))
		// .setText(AppMain.getInstance()._accountCurrent.getName());

		((TextView) findViewById(R.id.text_user_name)).setVisibility(View.GONE);

		_listViewMacAddress = (LinearLayout) findViewById(R.id.config_list_mac_address);		
		_buttonAddMacAddress = (Button) findViewById(R.id.button_config_add_mac_address);
		
		_buttonModifyMachineCode = (Button) findViewById(R.id.button_config_modify_machine_code);
		_buttonModifyPassword = (Button) findViewById(R.id.button_config_modify_password);
		_buttonModifyUsername = (Button) findViewById(R.id.button_config_modify_username);
		_buttonModifyDatabase = (Button) findViewById(R.id.button_config_modify_database_server_name);

		_TextUsername = (TextView) findViewById(R.id.text_config_username);
		_TextPassword = (EditText) findViewById(R.id.text_config_password);
		_TextMachineCode = (TextView) findViewById(R.id.text_config_machine_code);
		_TextDatabase = (TextView) findViewById(R.id.text_config_database_server_name);
		
		_TextMachineCode.setText(AppMain.getInstance().getMachineInfo().getCode());
		_TextPassword.setText(Network.getPassword());
		_TextUsername.setText(Network.getUsername());
		_TextDatabase.setText(Network.getDatabaseServer());

		_buttonAddMacAddress.setVisibility(View.GONE);

		_buttonModifyMachineCode.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Utils.debug("Modified device number!!!!!");

				_timerOutUtils.pause();

				startInputActivity(InputTextActivity.INPUT_MACHINE_CODE);
			}
		});

		_buttonModifyUsername.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{

				_timerOutUtils.pause();

				startInputActivity(InputTextActivity.INPUT_SERVER_USERNAME);
			}
		});

		_buttonModifyPassword.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{

				_timerOutUtils.pause();

				startInputActivity(InputTextActivity.INPUT_SERVER_PASSWORD);
			}
		});

		_buttonModifyDatabase.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{

				_timerOutUtils.pause();

				startInputActivity(InputTextActivity.INPUT_SERVER_DATABASE);
			}
		});

		_timerOutUtils = new TimerOutUtils(this, R.id.text_time, false);
	}

	private void startInputActivity(int inputType)
	{
		Intent intent = new Intent(AdminActivity.this,
				InputTextActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt(InputTextActivity.KEY_INPUT_TYPE, inputType);
		bundle.putInt(Constant.EXTRA_FINISH, 2);
		intent.putExtras(bundle);
		startActivityForResult(intent, inputType);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		_timerOutUtils.startTimerNotOperating();

		return super.onTouchEvent(event);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		switch (AppMain.getInstance().getCodeResult())
		{
			case TIME_OUT_NOT_OPERATOR:
				AppMain.getInstance().setNumberActivityFinishLogout(1);
				showDialogCatch(R.string.message_time_out_user_not_operating);

				break;
			case TIME_OUT_USER:
				AppMain.getInstance().setNumberActivityFinishLogout(1);
				showDialogCatch(R.string.message_time_out_user);

				break;
			default:
				break;
		}

		AppMain.getInstance().setCodeResult(CodeResult.NONE);

		super.onWindowFocusChanged(hasFocus);
	}

	private void showDialogCatch(final int id)
	{
		runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					showDialog(id);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});

	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_time_out_user)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_time_out_user_not_operating)
		{

			final DialogMessageConfirm dialogMessageConfirmNotOperating = new DialogMessageConfirm(
					this, false, id, true);
			OnClickListener onClickListenerYESNotOperating = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogMessageConfirmNotOperating.cancel();
					_timerOutUtils.stopTimeOutDialog();
					AppMain.getInstance().setNumberActivityFinishLogout(0);
				}
			};
			dialogMessageConfirmNotOperating.setOnclickListenerYes(onClickListenerYESNotOperating);
			return dialogMessageConfirmNotOperating;
		}
		else if (id == R.string.config_domain)
		{
			return new DialogEditDomainName(this,
					AppMain.getInstance().getMachineInfo().getDomainName());
		}
		else
			return createDialogStatusServer(id);
	}

	@Override
	protected void onPause()
	{
		_timerOutUtils.stop();

		super.onPause();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (KeyEvent.KEYCODE_MENU == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_LEFT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_CENTER == event.getKeyCode()
				|| KeyEvent.KEYCODE_CALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_CAMERA == event.getKeyCode()
				|| KeyEvent.KEYCODE_ENDCALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_HOME == event.getKeyCode()
				|| KeyEvent.KEYCODE_SEARCH == event.getKeyCode()
				|| KeyEvent.KEYCODE_BACK == event.getKeyCode())
		{
			return Utils.disableAllKey(event);
		}
		else
			return super.dispatchKeyEvent(event);

	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	@Override
	protected void onResume()
	{
		super.onResume();

		if (AppMain.getInstance().getNumberActivityFinishLogout() > 0)
		{
			AppMain.getInstance().setNumberActivityFinishLogout(AppMain.getInstance().getNumberActivityFinishLogout() - 1);
			finish();
			return;
		}

		_timerOutUtils.startTimerNotOperating();
		_timerOutUtils.startTimerOutUser();

		showListMacAddresses();
	}
	
	private void showListMacAddresses()
	{
		_listViewMacAddress.removeAllViews();

		final MachineInfo machine = AppMain.getInstance().getMachineInfo();

		final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		final View view1 = inflater.inflate(
				R.layout.layout_config_one_mac_address, null);
		final ViewHolderMacAddress holder1 = new ViewHolderMacAddress();
		holder1.buttonDelete = (Button) view1.findViewById(R.id.button_config_item_delete);
		holder1.buttonModify = (Button) view1.findViewById(R.id.button_config_item_modify);
		holder1.textMacAddress = (TextView) view1.findViewById(R.id.config_mac_item_address);
		
		if (AppConfig.IS_BLUETOOTH_SERIAL)
		{
			holder1.textMacAddress.setText(machine.getAddressPhysicalSerial());
		}
		else
		{
			holder1.textMacAddress.setText(machine.getAddressPhysical());
		}		

		holder1.buttonDelete.setVisibility(View.GONE);

		holder1.buttonModify.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				_timerOutUtils.pause();

				Intent intent = new Intent(AdminActivity.this,
						EditMacAddressActivity.class);				
				
				if (AppConfig.IS_BLUETOOTH_SERIAL)
				{
					intent.putExtra(EditMacAddressActivity.EXTRA_MAC_ADDRESS,
							machine.getAddressPhysicalSerial());
				}
				else
				{
					intent.putExtra(EditMacAddressActivity.EXTRA_MAC_ADDRESS,
							machine.getAddressPhysical());
				}	
				
				intent.putExtra(Constant.EXTRA_FINISH, 2);
				startActivityForResult(intent, REQUEST_EDIT_MAC_ADDRESS);
			}
		});

		_listViewMacAddress.addView(view1);
	}

	public void updateMacAddress(String address)
	{
		String[] strings = address.split("[:]");
		if (strings == null || strings.length != 6)
			return;

		final View view1 = _listViewMacAddress.getChildAt(0);
		final TextView textMacAddress = (TextView) view1.findViewById(R.id.config_mac_item_address);

		textMacAddress.setText(address);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode == RESULT_OK)
		{
			if (data == null)
			{
				Utils.debug("null data return!!!!!!!!!!!!!!!!!!1");
				return;
			}

			String dataString = (requestCode != REQUEST_EDIT_MAC_ADDRESS) ? data.getStringExtra(InputTextActivity.KEY_INPUT_DATA)
					: data.getStringExtra(EditMacAddressActivity.EXTRA_MAC_ADDRESS);

			_timerOutUtils.resume();

			if (dataString == null || dataString.equals(""))
			{
				Utils.debug("null data String!!!!!!!!!!!!!!!!!!1");

				return;
			}

			final MachineSQLite machineSQLite = new MachineSQLite(this);
			MachineInfo machine = null;

			try
			{
				machine = machineSQLite.getAll().get(0);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

			if (requestCode == REQUEST_EDIT_MAC_ADDRESS)
			{
				if (AppConfig.IS_BLUETOOTH_SERIAL)
				{
					machine.setAddressPhysicalSerial(dataString);
				}
				else
				{
					machine.setAddressPhysical(dataString);
				}

				updateMacAddress(dataString);

			}
			else if (requestCode == InputTextActivity.INPUT_MACHINE_CODE)
			{
				_TextMachineCode.setText(dataString);
				machine.setCode(dataString);

			}
			else if (requestCode == InputTextActivity.INPUT_SERVER_PASSWORD)
			{
				_TextPassword.setText(dataString);
				machine.setPasswordNetwork(dataString);

			}
			else if (requestCode == InputTextActivity.INPUT_SERVER_USERNAME)
			{
				_TextUsername.setText(dataString);
				machine.setUsernameNetwork(dataString);
			}
			else if (requestCode == InputTextActivity.INPUT_SERVER_DATABASE)
			{
				_TextDatabase.setText(dataString);
				machine.setDatabaseNetwork(dataString);
			}

			machineSQLite.insert(machine);
		}
	}

	@Override
	protected void onDestroy()
	{
		System.gc();
		super.onDestroy();
	}

	@Override
	public void onNetworkMessageIncomming(Transaction transaction)
	{		
	}

	@Override
	public void onConnectFail(int typeError)
	{		
	}

}
